package de.doegel.common;

import greendroid.graphics.drawable.ActionBarDrawable;
import greendroid.widget.ActionBarItem;
import greendroid.widget.ActionBarItem.Type;
import greendroid.widget.NormalActionBarItem;
import greendroid.widget.item.Item;

import java.sql.SQLException;
import java.util.List;
import java.util.Vector;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import de.doegel.common.model.Contact;
import de.doegel.common.ormlite.OrmLiteGDActivity;
import de.doegel.common.util.TextAndProgressBarUtils;
import de.doegel.common.util.Utils;
import de.doegel.common.widget.HeadedContactItem;
import de.doegel.common.widget.HeadedContactItemAdapter;

public class ContactsActivity<H extends AbstractDatabaseHelper> extends OrmLiteGDActivity<H> {
	private ListView listview = null;
	private View textandprogressbar = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setActionBarContentView(R.layout.contacts);
		setTitle(R.string.contacts_activity_title);

		addActionBarItem(getActionBar().newActionBarItem(NormalActionBarItem.class).setDrawable(new ActionBarDrawable(this, R.drawable.gd_action_bar_refresh)), R.id.action_bar_refresh);
		addActionBarItem(Type.Search, R.id.action_bar_search);

		listview = (ListView) findViewById(R.id.list);
		listview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
				Item item = (Item) parentView.getAdapter().getItem(position);
				Contact contact = (Contact) item.getTag();
				startActivity(Utils.createPersonIntent(ContactsActivity.this, contact.id, contact.name));
			}
		});

		textandprogressbar = (View) findViewById(R.id.text_and_progressbar);
		listview.setEmptyView(textandprogressbar);
		TextAndProgressBarUtils.initializeTextAndProgressBar(listview, textandprogressbar);
		
		new ReadContactsFromDBTask().execute();
	}

	@Override
	public boolean onHandleActionBarItemClick(ActionBarItem item, int position) {
		if (item.getItemId() == R.id.action_bar_refresh) {
			refreshContacts();
			return true;
		} else if (item.getItemId() == R.id.action_bar_search) {
			startActivity(Utils.createContactSearchIntent(this));
			return true;
		} else {
			return super.onHandleActionBarItemClick(item, position);
		}
	}

	public void refreshContacts() {
		new FetchTotalContactCountTask().execute();
	}

	public void onTextAndProgressBarClick(View view) {

	}	

	private class ReadContactsFromDBTask extends AsyncTask<Void, Void, List<HeadedContactItem>> {
		@Override
		protected List<HeadedContactItem> doInBackground(Void... params) {
			return Utils.createItems(getHelper());
		}

		@Override
		protected void onPostExecute(List<HeadedContactItem> result) {
			listview.setAdapter(new HeadedContactItemAdapter(ContactsActivity.this, result, IDoegelConstants.SECTIONS));
			TextAndProgressBarUtils.configureTextAndProgressBar(listview, getString(R.string.contacts_empty), false, false);
			super.onPostExecute(result);
		}
	}

	private class FetchTotalContactCountTask extends AsyncTask<Void, Void, Integer> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(ContactsActivity.this);
			dialog.setMessage(getString(R.string.contacts_importing));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					FetchTotalContactCountTask.this.cancel(true);
				}
			});
			dialog.show();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			return ((DoegelApplication) getApplication()).getHttpConnector().fetchTotalContact(ContactsActivity.this);
		}

		@Override
		protected void onPostExecute(Integer result) {
			if (!isCancelled() && result > 0) {
				try {
					getHelper().getContactDao().delete(getHelper().getContactDao().queryForAll());
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				new FetchContactsTask().execute(result);
			}
			dialog.dismiss();
			super.onPostExecute(result);
		}

		@Override
		public void onCancelled() {
		}
	}

	private class FetchContactsTask extends AsyncTask<Integer, Void, List<Contact>> {
		ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(ContactsActivity.this);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setMessage(getString(R.string.contacts_importing));
			dialog.setIndeterminate(false);
			dialog.setCancelable(true);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					FetchContactsTask.this.cancel(true);
				}
			});
			dialog.show();
		}

		@Override
		protected List<Contact> doInBackground(Integer... params) {
			List<Contact> contacts = new Vector<Contact>();
			int totalCount = params[0];
			if (totalCount <= 0)
				return contacts;
			dialog.setMax(totalCount);

			int offset = 0;
			while (true) {
				List<Contact> temp = ((DoegelApplication) getApplication()).getHttpConnector().fetchContacts(ContactsActivity.this, offset);
				offset += temp.size();
				contacts.addAll(temp);
				dialog.incrementProgressBy(temp.size());
				if (temp.size() < 25)
					break;
			}
			return contacts;
		}

		@Override
		protected void onPostExecute(List<Contact> result) {
			if (!isCancelled()) {
				try {
					for (int i = 0; i < result.size(); i++) {
						Contact contact =  result.get(i);
						Log.i("---c---", "go: "+contact.id);
						Contact c = getHelper().getContactDao().queryForId(contact.id);
						if (c == null) {
							getHelper().getContactDao().create((Contact) result.get(i));
						}
					}
					Log.i("---contacts---", "go: "+result.size());
					listview.setAdapter(new HeadedContactItemAdapter(ContactsActivity.this, Utils.createItems(getHelper()), IDoegelConstants.SECTIONS));
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}

			dialog.dismiss();

			super.onPostExecute(result);
		}

		@Override
		public void onCancelled() {
		}
	}

	private static final int CONTEXT_MENU_HOME = 0;
	private static final int CONTEXT_MENU_SETTINGS = 1;
	private static final int CONTEXT_MENU_REFRESH = 2;
	private static final int CONTEXT_MENU_SEARCH = 3;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, CONTEXT_MENU_HOME, 0, R.string.home_context_menu);
		menu.add(0, CONTEXT_MENU_SETTINGS, 0, R.string.settings_context_menu);
		menu.add(0, CONTEXT_MENU_REFRESH, 0, R.string.refresh_context_menu);
		menu.add(0, CONTEXT_MENU_SEARCH, 0, R.string.search_context_menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case CONTEXT_MENU_HOME:
			startActivity(Utils.createHomeIntent(this));
			return true;
		case CONTEXT_MENU_SETTINGS:
			startActivity(Utils.createSettingsIntent(this));
			finish();
			return true;
		case CONTEXT_MENU_REFRESH:
			refreshContacts();
			return true;
		case CONTEXT_MENU_SEARCH:
			startActivity(Utils.createContactSearchIntent(this));
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
